package com.cu.simpleerp.frame.session.impl;

import com.cu.simpleerp.frame.session.SessionManager;
import com.cu.simpleerp.system.model.User;
import com.cu.simpleerp.system.service.UserService;
import com.cu.simpleerp.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 默认session 管理器
 *
 * @author jintian
 * @date 2018/10/23 16:14
 */
@Component("defaultSession")
public class DefaultSessionManager implements SessionManager {

    private static String SESSION_KEY = "loginCookie";

    @Autowired
    private UserService userService;

    @Override
    public void refashSession(HttpServletRequest request) {
    }

    @Override
    public void removeSession(HttpServletRequest request) {

    }

    @Override
    public void addSession(HttpServletResponse response, HttpServletRequest request, String value) {
        HttpSession session = request.getSession();
        session.setAttribute(SESSION_KEY, value);
    }

    @Override
    public boolean checkSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        return session == null || StringUtils.isBlank((String) session.getAttribute(SESSION_KEY));
    }


    public User getLoginUser(HttpServletRequest request) {
        String userId = (String)request.getSession().getAttribute(SESSION_KEY);
        return  userService.queryById(Integer.valueOf(userId));
    }
}
